﻿using log4net;
using Mate.Caching;
using Mate.Core.Base;
using Mate.Core.Helper;
using Mate.Dto.Users;
using Mate.Framework.BaseController.Api;
using Mate.User.Api.Controller.Models.MpUser;
using Mate.User.Service;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Text;

namespace Mate.User.Api.Controller.Controller
{
    public class UserController: UserBaseController
    {
        private readonly ILog log;
        private readonly IMpUserService mpUserService;
        private readonly ICacheManager _cache;
        public UserController(ILog log, IMpUserService mpUserService, ICacheManager cache)
        {
            this.log = log;
            this.mpUserService = mpUserService;
            this._cache = cache; 
        }

        #region 用户登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public BaseResult<MpUserLoginDto> Login(LoginRequest req)
        {
            BaseResult<MpUserLoginDto> result = new BaseResult<MpUserLoginDto>();
            if (string.IsNullOrWhiteSpace(req.username)|| string.IsNullOrWhiteSpace(req.password))
            {
                result.ResultCode = ResultCode.ParamError;
                result.Message = "参数错误";
                return result;
            }
            string pwd = EncryptionHelper.MD5(req.password);
            var userModel = mpUserService.Queryable.Where(x => x.username == req.username && x.password == pwd).First();
            if (userModel == null || userModel.id == 0)
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "用户名或密码错误";
                return result;
            }

            string token = TokenHelper.GetToken();
            var loginDto= new MpUserLoginDto()
            {
                userid = userModel.id,
                token = token,
                lever = userModel.lever,
                nickname = userModel.nickname,
                usericon = userModel.usericon,
                username = userModel.username
            };
            _cache.Set(token, loginDto, (24 * 60));
            result.ResultCode = ResultCode.Success;
            result.Message = "登录成功";
            result.Data = loginDto;
            return result;
        }
        #endregion

    }
}
